package cn.cslg.weatherforecast.service;

import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Binder;
import android.os.IBinder;

import cn.cslg.weatherforecast.R;

public class MusicService extends Service {
    MediaPlayer mp;
    IBinder binder = new MyBinder();

    //应用程序通过该对象与Service组件通信
    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
//        throw new UnsupportedOperationException("Not yet implemented");
        return binder;
    }

    public class MyBinder extends Binder {
        public MusicService getService() {
            return MusicService.this;
        }
    }

    //每次客户端调用startService方法时回调
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        play();
        return super.onStartCommand(intent, flags, startId);
    }

    public void play() {
        mp = MediaPlayer.create(this, R.raw.music);
        mp.start();
        mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) {
                Intent intent = new Intent("musicover");
                sendBroadcast(intent);
            }
        });
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mp.isPlaying()) mp.stop();
        mp.release();
    }
}
